/*
 * Diagrama_Configure.java
 *
 * Created on June 9, 2007, 11:52 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.jerm.Interface.JGraph_Diagrama;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.net.URL;
import java.util.ArrayList;

import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.jerm.Mapeamento.Atributos.Atributo;
import org.jerm.Mapeamento.Atributos.AtributoCaracter;
import org.jerm.Mapeamento.Atributos.AtributoDecimal;
import org.jerm.Mapeamento.Atributos.AtributoEnum;
import org.jerm.Mapeamento.Atributos.AtributoNumero;
import org.jerm.Mapeamento.Atributos.AtributoSerial;
import org.jerm.Mapeamento.Atributos.AtributoTexto;

/**
 *
 * @author tiagofalcao
 */
public class Diagrama_Configure extends JPanel 
                      implements ListSelectionListener, ItemListener, ActionListener  {
    private MyGraph graph;
    
    private Class<?> classe;
    protected Object bloco;
    protected JLabel Nome;
    protected boolean hasPrimo=true;
    
    protected Object[] AtributosPrimos;
    protected Object[] Atributos;
    protected ArrayList<JListItem> Atributos_JList;
    protected ArrayList<AtributoSerial> Atributos_Tipos;
    
    protected JScrollPane Scroll_Lista_Atributos;
    protected JList Lista_Atributos;
    protected Object[] Lista;
    protected int Lista_np;
    
    protected JButton addAtributo;
    protected JButton remAtributo;
    
    
    public ImageIcon icon_key  = new ImageIcon(getClass().getClassLoader().getResource("org/jerm/Interface/Icones/key.gif"));
    public ImageIcon sicon_key  = new ImageIcon(getClass().getClassLoader().getResource("org/jerm/Interface/Icones/key.gif"));
    public ImageIcon icon_atr  = new ImageIcon(getClass().getClassLoader().getResource("org/jerm/Interface/Icones/port.gif"));
    public ImageIcon sicon_atr  = new ImageIcon(getClass().getClassLoader().getResource("org/jerm/Interface/Icones/port.gif"));

    
    private javax.swing.JCheckBox MultiValorado;
    private javax.swing.JCheckBox Chave;
    private javax.swing.JCheckBox Nulo;
    private javax.swing.JCheckBox Unico;
    private javax.swing.JCheckBox Unsigned;
    private javax.swing.JCheckBox Zerofill;
    private boolean bNulo;
    private boolean bUnsigned;
    private boolean bZerofill;
    private javax.swing.JComboBox Tipo;
    private javax.swing.JLabel nTipo;
    private javax.swing.JLabel nNomeAtr;
    private javax.swing.JTextField NomeAtr;
    
    GridBagConstraints c;
    
    /** Creates a new instance of Diagrama_Configure */
    public Diagrama_Configure(MyGraph graph) {
        super();
        this.graph=graph;
        
        build();
    }

    private void build(){
        this.bloco=graph.getSelectionCells()[0];
        if(bloco==null)
            return;
        
        classe=bloco.getClass();
        createName(graph.convertValueToString(bloco));
        
        if(classe==Relacionamento.class && !((Relacionamento)bloco).isTotal()){ //Bloqueia Atributos de Relacionamento Total
            hasPrimo=((Relacionamento)bloco).isAssociativa();
        }else if(classe!=Entidade.class){
            return;
        }
        
        nNomeAtr = new javax.swing.JLabel();
        nNomeAtr.setText("Nome");
        NomeAtr = new javax.swing.JTextField();
        this.NomeAtr.addActionListener(this);
        nTipo = new javax.swing.JLabel();
        nTipo.setText("Tipo");
        Tipo = new javax.swing.JComboBox();
        Chave = new javax.swing.JCheckBox();
        Chave.setText("Chave");
        Chave.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        Chave.setMargin(new java.awt.Insets(0, 0, 0, 0));
        Chave.addItemListener(this);
        MultiValorado = new javax.swing.JCheckBox();
        MultiValorado.setText("MultiValorado");
        MultiValorado.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        MultiValorado.setMargin(new java.awt.Insets(0, 0, 0, 0));
        MultiValorado.addItemListener(this);
        Nulo = new javax.swing.JCheckBox();
        Nulo.setText("Nulo");
        Nulo.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        Nulo.setMargin(new java.awt.Insets(0, 0, 0, 0));
        Nulo.addItemListener(this);
        Unico = new javax.swing.JCheckBox();
        Unico.setText("Unico");
        Unico.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        Unico.setMargin(new java.awt.Insets(0, 0, 0, 0));
        Unico.addItemListener(this);
        Unsigned = new javax.swing.JCheckBox();
        Unsigned.setText("Unsigned");
        Unsigned.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        Unsigned.setMargin(new java.awt.Insets(0, 0, 0, 0));
        Unsigned.addItemListener(this);
        Zerofill = new javax.swing.JCheckBox();
        Zerofill.setText("Zerofill");
        Zerofill.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        Zerofill.setMargin(new java.awt.Insets(0, 0, 0, 0));
        Zerofill.addItemListener(this);
        Tipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] {"varchar","char",
                                                                "boolean", "smallint", "int", "bigint", 
                                                                "serial", "bigserial", 
                                                                "float", "double", "decimal", "numeric",
                                                                "text",   "enum", "set" }));
        Tipo.addActionListener(this);
        
        createAtributosList();
        createList();
        createAddAtributo();
        createRemAtributo();
        setComponentes();
        this.updateUI();
    }
    
    private void setComponentes(){ // vvv Comentar quando der pau
        this.setLayout(new GridBagLayout());
        c = new GridBagConstraints();
        c.fill = GridBagConstraints.HORIZONTAL;
        
        
        c.insets=new Insets(5,5,1,1);
        c.gridx = 0; //posicao x na linha
        c.gridy = 0; //posicao y na linha
        c.gridwidth = 3;
        this.add(Nome, c);
        
            ///////////////
            c.gridy++;//Nova Linha
            //////////////
        
        c.gridx = 0;
        c.gridwidth = 2;
        //c.gridheight=2;
        this.add(Scroll_Lista_Atributos, c);
        
        c.gridwidth = 1;
        c.weightx = 0.0;
        c.anchor = GridBagConstraints.SOUTH;
        c.gridx = 2;
        this.add(addAtributo, c);
        //c.anchor=GridBagConstraints.CENTER;
        
//            ///////////////
//            c.gridy++;//Nova Linha
//            //////////////
        c.gridwidth = 1;
        c.weightx = 0.0;
        c.anchor = GridBagConstraints.NORTH;
        c.gridx = 2;
        this.add(remAtributo, c);
        c.anchor=GridBagConstraints.CENTER;
        
        boolean hasSelection=! Lista_Atributos.isSelectionEmpty();
        
        if(hasSelection){
            ///////////////
            c.gridy++;//Nova Linha
            //////////////
            c.gridx = 0; //posicao x na linha
            c.ipadx = 15;
            this.add(nNomeAtr, c);

            c.gridx = 1;
            c.gridwidth = 2;
            //c.ipadx = 120;
            this.add(NomeAtr, c);

            ///////////////
            c.gridy++;//Nova Linha
            //////////////
            
            c.ipadx = 0;
            c.weightx = 0.0;
            c.gridx = 0;
            c.gridwidth = 1;
            this.add(nTipo, c);

            c.gridx = 1;
            c.gridwidth = 2;
            this.add(Tipo, c);

            ///////////////
            c.gridy++;//Nova Linha
            //////////////
            
            c.gridx = 0;
            c.gridwidth=3;
            
            if(hasPrimo){
                this.add(Chave,c);

                ///////////////
                c.gridy++;//Nova Linha
                //////////////
                
            }
            
            this.add(MultiValorado,c);
            
            ///////////////
            c.gridy++;//Nova Linha
            //////////////
            
            this.add(Unico,c);
            
            ///////////////
            c.gridy++;//Nova Linha
            //////////////
            
            if(bUnsigned){
                this.add(Unsigned,c);

                ///////////////
                c.gridy++;//Nova Linha
                //////////////
                
            }
            
            if(bZerofill){
                this.add(Zerofill,c);

                ///////////////
                c.gridy++;//Nova Linha
                //////////////
                
            }
            
            if(bNulo){
                this.add(Nulo,c);

                ///////////////
                c.gridy++;//Nova Linha
                //////////////
                
            }
        }
    } 
    
    private void iniAtrComponentes(){
        this.NomeAtr.removeActionListener(this);
        this.NomeAtr.setText(((JListItem)Lista_Atributos.getSelectedValue()).Nome);
        this.NomeAtr.addActionListener(this);
        
        Chave.removeItemListener(this);
        this.Chave.setSelected(((JListItem)Lista_Atributos.getSelectedValue()).Chave);
        Chave.addItemListener(this);
        
        Unico.removeItemListener(this);
        this.Unico.setSelected(((JListItem)Lista_Atributos.getSelectedValue()).Chave);
        Unico.addItemListener(this);
        
        if(Chave.isSelected()){
            this.MultiValorado.setSelected(false);
            this.MultiValorado.setEnabled(false);
        }else{
            this.MultiValorado.setEnabled(true);
            MultiValorado.removeItemListener(this);
            this.MultiValorado.setSelected(((Atributo)((JListItem)Lista_Atributos.getSelectedValue()).Atributo).MultiValorado);
            MultiValorado.addItemListener(this);
        }
        
        Tipo.removeActionListener(this);
        Tipo.setSelectedItem(((Atributo)((JListItem)Lista_Atributos.getSelectedValue()).Atributo).getTipo());
        Tipo.addActionListener(this);
        
        if(bUnsigned){
            Unsigned.removeActionListener(this);
            Unsigned.setSelected(((AtributoNumero)((JListItem)Lista_Atributos.getSelectedValue()).Atributo).getUnsigned());
            Unsigned.addActionListener(this);
        }
        
        if(bZerofill){
            Zerofill.removeActionListener(this);
            Zerofill.setSelected(((AtributoNumero)((JListItem)Lista_Atributos.getSelectedValue()).Atributo).getZerofill());
            Zerofill.addActionListener(this);
        }
        
        if(bNulo){
            Nulo.removeActionListener(this);
            if(((JListItem)Lista_Atributos.getSelectedValue()).Atributo.getClass()==AtributoTexto.class ||
                    ((JListItem)Lista_Atributos.getSelectedValue()).Atributo.getClass()==AtributoCaracter.class ||
                    ((JListItem)Lista_Atributos.getSelectedValue()).Atributo.getClass()==AtributoEnum.class){
                Nulo.setSelected(((AtributoTexto)((JListItem)Lista_Atributos.getSelectedValue()).Atributo).getNulo());
            }else{
                Nulo.setSelected(((AtributoNumero)((JListItem)Lista_Atributos.getSelectedValue()).Atributo).getNulo());
            }
            Nulo.addActionListener(this);
        }
    }
    private void removeAtrComponentes(){
        this.remove(nNomeAtr);
        this.remove(NomeAtr);
        this.remove(nTipo);
        this.remove(Tipo);
        this.remove(Chave);
        this.remove(MultiValorado);
        this.remove(Unico);
        this.remove(Nulo);
        this.remove(Unsigned);
        this.remove(Zerofill);
    }
    
    public void createName(String Nome){
        this.Nome=new JLabel(Nome);
        this.Nome.setHorizontalAlignment(SwingConstants.CENTER);
    }
    
    ////////////////////////////////////////////////////
    //
    // Atributos
    //
    
    private void createAtributosList() {
         AtributosPrimos=((BlocoAtributosGraphCell)bloco).valuesArrayAtributosPrimos();
         Atributos=((BlocoAtributosGraphCell)bloco).valuesArrayAtributos();
         
         Atributos_JList=new ArrayList<JListItem>();
         int i=0;
         if(hasPrimo)
             while(i<AtributosPrimos.length){
                 Atributos_JList.add(new JListItem(((Atributo)AtributosPrimos[i]).getNome(),AtributosPrimos[i],true,icon_key,sicon_key));
                 i++;
             }
//         else
//             while(i<AtributosPrimos.length){
//                 Atributos_JList.add(new JListItem(((Atributo)AtributosPrimos[i]).getNome(),AtributosPrimos[i],false,icon_atr,sicon_atr));
//                 i++;
//             }
         i=0;
         Lista_np=Atributos_JList.size();
         while(i<Atributos.length){
             Atributos_JList.add(new JListItem(((Atributo)Atributos[i]).getNome(),Atributos[i],false,icon_atr,sicon_atr));
             i++;
         }
         Lista=Atributos_JList.toArray();
    }
    
    private void createList(){
        Lista_Atributos= new JList(Lista);
        Lista_Atributos.setVisibleRowCount(8);
        Lista_Atributos.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        Lista_Atributos.setCellRenderer(new JListRenderer());
        Lista_Atributos.addListSelectionListener(this);
        
        Scroll_Lista_Atributos= new JScrollPane(Lista_Atributos,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        Scroll_Lista_Atributos.setPreferredSize(new Dimension(165,200));
    }
    private void createAddAtributo(){
        EventRedirector copy;
        AbstractAction action;
        URL iconUrl;
        ImageIcon imageIcon;
        AbstractAction add;
        
        
        action = new AbstractAction(""){
                public void actionPerformed(ActionEvent e) {
                    addAtributo();
                }
        };
        iconUrl = getClass().getClassLoader().getResource("org/jerm/Interface/Icones/plus.gif");
        addAtributo = new JButton("");
        addAtributo.setAction (action);
        addAtributo.setIcon (new ImageIcon(iconUrl));
        addAtributo.setPreferredSize(new Dimension(20,20));
    }
    
    protected void addAtributo(){
        Integer size=new Integer(AtributosPrimos.length + Atributos.length);
        AtributoNumero Atributo=new AtributoNumero();
        Atributo.setNome("Atributo"+size);
        try {
            Atributo.setTipo("int");
        } catch (Exception ex) {
        }
        boolean boo=((BlocoAtributosGraphCell)bloco).addAtributo(Atributo);
        
        createAtributosList();
        Lista_Atributos.setListData(Lista);
        
        int i=Lista.length-1;
        while(i>=0 && ((JListItem)Lista[i]).Nome!=Atributo.getNome()){
            i--;
        }
        Lista_Atributos.setSelectedIndex(i);
        
    }
    private void createRemAtributo(){
        EventRedirector copy;
        AbstractAction action;
        URL iconUrl;
        ImageIcon imageIcon;
        AbstractAction add;
        
        
        action = new AbstractAction(""){
                public void actionPerformed(ActionEvent e) {
                    remAtributo();
                }
        };
        iconUrl = getClass().getClassLoader().getResource("org/jerm/Interface/Icones/delete.gif");
        remAtributo = new JButton("");
        remAtributo.setAction (action);
        remAtributo.setIcon (new ImageIcon(iconUrl));
        remAtributo.setPreferredSize(new Dimension(20,20));
        remAtributo.setEnabled(false);
    }
    
    protected void remAtributo(){
        int i=Lista_Atributos.getSelectedIndex();
        ((BlocoAtributosGraphCell)bloco).removeAtributo(((JListItem)Lista_Atributos.getSelectedValue()).Nome);
        
        createAtributosList();
        Lista_Atributos.setListData(Lista);
        if(Lista.length>0){
            if(i>=Lista.length){
                i=Lista.length-1;
            }
            Lista_Atributos.setSelectedIndex(i);
        }
        
    }
    
    ////////////////////////////////////////////////////////
    //
    // Panel de Edicao do Nome
    //
    private void createAtributoPanel(){
        
    }

    private void updateAtrOptions(JListItem item){
        Object a=item.Atributo;
        if(a.getClass()==AtributoNumero.class || a.getClass()==AtributoDecimal.class  || a.getClass()==AtributoTexto.class
                || a.getClass()==AtributoCaracter.class || a.getClass()==AtributoEnum.class)
            bNulo=true;
        else
            bNulo=false;
        
        if(a.getClass()==AtributoNumero.class || a.getClass()==AtributoDecimal.class){
            bUnsigned=true;
            bZerofill=true;
        }else{
            bUnsigned=false;
            bZerofill=false;
        }
        
    }
    
    public void valueChanged(ListSelectionEvent e) {
        if(!Lista_Atributos.isSelectionEmpty()){
            JListItem s=(JListItem)Lista_Atributos.getSelectedValue();
            updateAtrOptions(s);
            iniAtrComponentes();
            remAtributo.setEnabled(true);
            
            }else{
            removeAtrComponentes();
            remAtributo.setEnabled(false);
        }
        setComponentes();
        this.updateUI();
    }

    public void itemStateChanged(ItemEvent e) {
        Object source = e.getItemSelectable();
        if(source==Chave){
            int i=Lista_Atributos.getSelectedIndex();
            JListItem s=((JListItem)Lista[i]);
            ((BlocoAtributosGraphCell)bloco).setPrimo(s.Nome,!s.Chave);
            createAtributosList();
            Lista_Atributos.setListData(Lista);
            i=Lista.length-1;
            while(i>=0 && ((JListItem)Lista[i]).Nome!=s.Nome){
                i--;
            }
            Lista_Atributos.setSelectedIndex(i);
            if(Chave.isSelected()){
                this.MultiValorado.setSelected(false);
                this.MultiValorado.setEnabled(false);
            }else{
                this.MultiValorado.setEnabled(true);
            }
        }else if(source==MultiValorado){
            ((Atributo)((JListItem)Lista_Atributos.getSelectedValue()).Atributo).MultiValorado=MultiValorado.isSelected();
        }else if(source==Unico){
            ((AtributoSerial)((JListItem)Lista_Atributos.getSelectedValue()).Atributo).setUnico(Unico.isSelected());
        }else if(source==Unsigned){
            ((AtributoNumero)((JListItem)Lista_Atributos.getSelectedValue()).Atributo).setUnsigned(Unsigned.isSelected());
        }else if(source==Zerofill){
            ((AtributoNumero)((JListItem)Lista_Atributos.getSelectedValue()).Atributo).setZerofill(Zerofill.isSelected());
        }else if(source==Nulo){
            if(((JListItem)Lista_Atributos.getSelectedValue()).Atributo.getClass()==AtributoTexto.class ||
                    ((JListItem)Lista_Atributos.getSelectedValue()).Atributo.getClass()==AtributoCaracter.class ||
                    ((JListItem)Lista_Atributos.getSelectedValue()).Atributo.getClass()==AtributoEnum.class){
                ((AtributoTexto)((JListItem)Lista_Atributos.getSelectedValue()).Atributo).setNulo(Nulo.isSelected());
            }else{
                ((AtributoNumero)((JListItem)Lista_Atributos.getSelectedValue()).Atributo).setNulo(Nulo.isSelected());
            }
        }
    }

    public void actionPerformed(ActionEvent e) {
        Object s = e.getSource();
        if(s==Tipo){
            String Nome=((JListItem)Lista_Atributos.getSelectedValue()).Nome;
            ((BlocoAtributosGraphCell)this.bloco).changeAtributo(Nome,(String)Tipo.getSelectedItem());
            createAtributosList();
            Lista_Atributos.setListData(Lista);
            
            int i=Lista.length-1;
            while(i>=0 && ((JListItem)Lista[i]).Nome!=Nome){
                i--;
            }
            Lista_Atributos.setSelectedIndex(i);
            updateAtrOptions(((JListItem)Lista[i]));
            iniAtrComponentes();
        }else if(s==NomeAtr){
            String NovoNome=NomeAtr.getText();
            boolean ok=((BlocoAtributosGraphCell)this.bloco).renameAtributo(((JListItem)Lista_Atributos.getSelectedValue()).Nome,NovoNome);

            if(ok){
                createAtributosList();
                Lista_Atributos.setListData(Lista);

                int i=Lista.length-1;
                while(i>=0 && ((JListItem)Lista[i]).Nome!=NovoNome){
                    i--;
                }
                Lista_Atributos.setSelectedIndex(i);
            }else{
                NomeAtr.removeActionListener(this);
                NomeAtr.setText(((JListItem)Lista_Atributos.getSelectedValue()).Nome);
                NomeAtr.addActionListener(this);
            }
        }
    }
}
